package ds.queue;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: 用数组实现队列
 * @date 2022/9/12 17:34
 */
public class ArrayQueue {

    private final ReentrantLock lock = new ReentrantLock(true);

    private final Object[] items;

    private final int length;

    // 头结点坐标
    private int head;

    // 尾结点坐标
    private int tail;

    public ArrayQueue(Object[] items, int length) {
        this.items = items;
        this.length = length;
    }

    // 入队操作,当尾节点坐标到达最后会触发数据迁移
    public boolean push(Object o){
        lock.lock();
        try {
            if(tail == length-1){
                if(head == 0){
                    return false;
                }
                // 数据搬移
                for(int i = head;i<tail;head++){
                    items[tail-head] = items[i];
                }
                // 更新头节点坐标和尾节点坐标
                tail -= head;
                head = 0;
            }
            items[tail] = o;
            ++tail;
        } finally {
            lock.unlock();
        }
        return true;
    }

    // 出队操作
    public Object pop(){
        Object o;
        lock.lock();
        try {
            if(head == tail)
                return null;
            o = items[head];
            ++head;
        } finally {
            lock.unlock();
        }
        return o;
    }

    public static void main(String[] args) {
        Object[] items = {1,2,3,4,5};
        ArrayQueue arrayQueue = new ArrayQueue(items, 5);
        for (int i = 1; i <= 5; i++) {
            Object o = arrayQueue.pop();
            System.out.println("第"+ i + "次pop,"+"结果为"+o);
        }
    }

}
